<script setup lang="ts">
import jsonData from "#/index.json"
import { onMounted, ref, watch } from "vue"
import { formRules } from "./rules"
import { cloneDeep } from "lodash-es"
import { ElMessage, FormInstance } from "element-plus"
import { useRouter } from "vue-router"
import previewPdf from "@/components/PreviewPdf/index.vue"

import { addressCascaderOpts, getAddressDetails } from "@/utils/transform"
import { usePagination } from "@/hooks/usePagination"
import { DeliveryUserDataParams, DeliveryUserRecord } from "@/api/company/types/interview"
import { getDeliveryUserList, handleCompanyApprove } from "@/api/company/interview"
import { InterviewStatus, InterviewResultStatus } from "./type"

const router = useRouter()
const { paginationData, handleCurrentChange } = usePagination({
  current: 1,
  layout: "total, prev, pager, next, jumper"
})

// #region 查询岗位
const DEFAULT_FORM_PARAMS: DeliveryUserDataParams = {
  id: "",
  gender: undefined as unknown as number,
  studyingExperience: undefined,
  workName: "",
  workTime: undefined as unknown as number,
  workAddress: "[]",
  workPrice: undefined as unknown as number
}
const cascaderOpts = ref()
const searchFormRef = ref<FormInstance | null>()
const searchformData = ref(cloneDeep(DEFAULT_FORM_PARAMS))
const deliverUserData = ref<DeliveryUserRecord[]>([])
const getResourecLabel = (val: number | string, resource: { value: number; label: string }[]) => {
  if (val === undefined) val = "1"
  const [tagItem] = resource.filter((item) => item.value === Number(val))
  return tagItem.label
}

function getDeliverUserData() {
  const paginationParams = {
    current: paginationData.current,
    pageSize: paginationData.pageSize,
    sortOrder: "desc"
  }
  getDeliveryUserList({ ...searchformData.value, ...paginationParams }).then(({ data }) => {
    deliverUserData.value = data.records
    paginationData.total = Number(data.total)
  })
}

function resetSearch() {
  searchFormRef.value?.resetFields()
  getDeliverUserData()
}

watch(
  () => paginationData.current,
  () => {
    getDeliverUserData()
  },
  {
    immediate: true
  }
)

onMounted(() => {
  cascaderOpts.value = addressCascaderOpts
})
// #endregion

// #region 企业面试操作
const previewPdfRef = ref()
const isDisableBtn = (
  progressCode: InterviewStatus,
  resultCode: InterviewResultStatus
): [boolean, boolean, boolean] => {
  if (resultCode === InterviewResultStatus.Pass || resultCode === InterviewResultStatus.Refuse)
    return [true, true, true]
  if (resultCode === InterviewResultStatus.Unknown) {
    if (progressCode === InterviewStatus.Deliver) {
      return [false, true, false]
    }
    if (progressCode === InterviewStatus.PendingApproval) {
      return [true, true, false]
    }
    if (progressCode === InterviewStatus.Proceed) {
      return [true, false, false]
    }
    if (progressCode === InterviewStatus.Finished) {
      return [true, false, false]
    }
  }
  return undefined as never
}

function handleInterviewOptions(deliverUserId: string, type: "invite" | "pass" | "reject") {
  const [deliverUser] = deliverUserData.value.filter((item) => item.id === deliverUserId)
  const fixParams = {
    companyWorkId: Number(deliverUser.companyWorkVO.id),
    userId: Number(deliverUser.userDetailVO.userVO.id),
    interviewResult: type === "reject" ? 1 : 2
  }
  handleCompanyApprove(fixParams).then(({ data }) => {
    if (data) {
      ElMessage({ type: "success", message: "操作成功" })
      getDeliverUserData()
    }
  })
}

function openPdfFile(id: string) {
  const [currentUser] = deliverUserData.value.filter((item) => item.id === id)
  const pdfUrl = currentUser?.userDetailVO?.profile
  if (pdfUrl) {
    previewPdfRef.value?.handleOpenResumePdf(pdfUrl)
  }
}
// #endregion
</script>

<template>
  <div class="app-container">
    <el-card class="search-card" shadow="never">
      <el-form ref="searchFormRef" :model="searchformData" :rules="formRules" :inline="true">
        <el-form-item label="职位名称" prop="workName">
          <el-input v-model="searchformData.workName" style="width: 170px" placeholder="请输入职位名称" clearable />
        </el-form-item>
        <el-form-item label="学历" prop="studyingExperience">
          <el-select
            v-model="searchformData.studyingExperience"
            style="width: 130px"
            placeholder="请选择学历"
            clearable
          >
            <el-option
              v-for="{ value, label } in jsonData.studyacademicDegree"
              :key="value"
              :label="label"
              :value="value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="searchformData.gender" style="width: 150px" placeholder="请选择性别" clearable>
            <el-option v-for="{ value, label } in jsonData.gender" :key="value" :label="label" :value="value" />
          </el-select>
        </el-form-item>
        <el-form-item label="工作经验" prop="workTime">
          <el-select v-model="searchformData.workTime" style="width: 170px" placeholder="请选择工作经验范围" clearable>
            <el-option v-for="{ value, label } in jsonData.workTime" :key="value" :label="label" :value="value" />
          </el-select>
        </el-form-item>
        <el-form-item label="工作区域" prop="workAddress">
          <el-cascader
            :options="cascaderOpts"
            v-model="searchformData.workAddress as any"
            style="width: 320px"
            clearable
          />
        </el-form-item>
        <el-form-item label="薪资范围" prop="workPrice">
          <el-select v-model="searchformData.workPrice" placeholder="请选择薪资范围" style="width: 200px" clearable>
            <el-option v-for="{ label, value } in jsonData.workPrice" :key="value" :value="value" :label="label" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getDeliverUserData">筛选</el-button>
          <el-button plain @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <div class="deliver-user-wrapper">
      <el-card class="deliver-user-empty" v-if="deliverUserData.length === 0" shadow="never">
        <el-empty description="空数据" />
      </el-card>
      <el-card
        class="deliver-user-card"
        v-else
        v-for="{ companyWorkVO, userDetailVO, id, flowStatus, interviewResult } in deliverUserData"
        :key="id"
        shadow="hover"
        body-class="deliver-user-card__content"
      >
        <el-card class="position-card" shadow="never">
          <template #header>
            <div class="card-header">
              <el-row justify="space-between">
                <el-col :span="18">
                  <el-text class="fw-700" type="primary" size="large">{{ companyWorkVO.workName }}</el-text>
                </el-col>
                <el-col :span="6">
                  <el-text type="info">薪资范围</el-text>
                  &nbsp;
                  <el-text>{{ getResourecLabel(companyWorkVO.workPrice!, jsonData.workPrice) }}</el-text>
                </el-col>
              </el-row>
            </div>
          </template>
          <div class="position-card__content">
            <div class="work">
              <el-text class="fw-700">工作描述</el-text>
              <div class="work-details" v-html="companyWorkVO.workDescription" />
            </div>
            <div class="work-tag">
              <div class="flex gap-2">
                <el-tag class="academic-degree" type="info">{{
                  getResourecLabel(String(companyWorkVO.studyingExperience), jsonData.studyacademicDegree)
                }}</el-tag>
                <el-tag class="work-experience" type="info">
                  {{ getResourecLabel(String(companyWorkVO.workTime), jsonData.workTime) }}
                </el-tag>
              </div>
            </div>
          </div>
          <template #footer>
            <el-row justify="space-between" align="middle">
              <el-col :span="18">
                <div>
                  <span class="company">
                    <svg-icon name="company" />
                    {{ companyWorkVO.companyVO.companyShortName }}
                  </span>
                  &nbsp;
                  <span
                    v-show="Array.isArray(companyWorkVO.workAddress) && companyWorkVO.workAddress.length !== 0"
                    class="address"
                  >
                    <svg-icon name="address" />
                    <span style="font-size: 14px">{{ getAddressDetails(companyWorkVO.workAddress as any) }}</span>
                  </span>
                </div>
              </el-col>
              <el-col :span="6">
                <el-button plain @click="router.push(`/post-details/${companyWorkVO.id}`)">查看岗位</el-button>
              </el-col>
            </el-row>
          </template>
        </el-card>
        <el-card class="user-card" shadow="never">
          <template #header>
            <img
              class="user-avatar"
              :src="userDetailVO.userVO?.userAvatar"
              width="50"
              height="50"
              alt="用户头像"
              decoding="async"
            />
            <el-text>{{ userDetailVO.userVO?.userName }}</el-text>
          </template>
          <div class="user-card__content">
            <el-descriptions :column="2">
              <el-descriptions-item label="性别">{{
                getResourecLabel(userDetailVO.userVO?.gender!, jsonData.gender)
              }}</el-descriptions-item>
              <el-descriptions-item label="学历">
                {{ getResourecLabel(userDetailVO.studyingExperience, jsonData.studyacademicDegree) }}
              </el-descriptions-item>
              <el-descriptions-item label="工作经验">
                {{ getResourecLabel(userDetailVO.workTime, jsonData.workTime) }}
              </el-descriptions-item>
              <el-descriptions-item label="期望薪资">
                {{ getResourecLabel(userDetailVO.workPrice, jsonData.workPrice) }}
              </el-descriptions-item>
              <el-descriptions-item label="面试进度">
                {{ getResourecLabel(flowStatus, jsonData.interviewProcess) }}
              </el-descriptions-item>
              <el-descriptions-item label="面试结果">
                {{ getResourecLabel(interviewResult, jsonData.interview) }}
              </el-descriptions-item>
              <template #extra>
                <el-button @click="openPdfFile(id)" plain>查看简历</el-button>
              </template>
            </el-descriptions>
          </div>
          <template #footer>
            <el-button
              type="primary"
              @click="handleInterviewOptions(id, 'invite')"
              :disabled="isDisableBtn(flowStatus, interviewResult)[0]"
              text
              >邀请面试</el-button
            >
            <el-button
              type="success"
              @click="handleInterviewOptions(id, 'pass')"
              :disabled="isDisableBtn(flowStatus, interviewResult)[1]"
              text
              >通过面试</el-button
            >
            <el-button
              type="danger"
              @click="handleInterviewOptions(id, 'reject')"
              :disabled="isDisableBtn(flowStatus, interviewResult)[2]"
              text
              >拒绝</el-button
            >
          </template>
        </el-card>
      </el-card>
    </div>
    <el-card class="pager-wrapper" shadow="never">
      <el-pagination
        background
        :layout="paginationData.layout"
        :total="paginationData.total"
        :page-size="paginationData.pageSize"
        :current-page="paginationData.current"
        @current-change="handleCurrentChange"
      />
    </el-card>
    <teleport to="body">
      <preview-pdf ref="previewPdfRef" />
    </teleport>
  </div>
</template>

<style scoped lang="scss" src="./style.scss"></style>
